package com.egao.api.controller;


import com.egao.common.core.damon.constant.UserConstant;
import com.egao.common.core.web.BaseController;
import com.egao.common.core.web.JsonResult;
import com.egao.common.system.entity.User;
import com.egao.gzh.service.Wxservice;
import com.egao.gzh.utils.AesException;
import com.egao.gzh.utils.WXPublicUtils;
import com.egao.orderB.entity.CustomerCopy;
import com.egao.orderB.entity.Driver;
import com.egao.orderB.service.CustomerService;
import com.egao.orderB.service.DriverService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * api登录相关接口
 * Created by lining on 2019-05-29 下午 3:43.
 * http://localhost/swagger-ui.html
 * http://192.168.1.110/swagger-ui.html
 */
@RequestMapping("/api/nt/login")
@RestController
@Api(value = "登录Api",tags = {"登录Api"})
public class ApiLoginController extends BaseController {

//    @Qualifier("jdbcTokenStore")
//    @Autowired
//    private TokenStore tokenStore;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private DriverService driverService;
    @Autowired
    private Wxservice wxservice;


    /**
     * web注册用户
     */
    @ApiOperation(value = "web端(货代,车队,报关行,订舱代理)注册  注册客户只有这个入口 没有手动添加",notes = "" +
            "username 帐号 必填\n" +
            "password 密码 必填\n" +
            "phone 电话 必填\n" +
            "type 类型:车队,货代,报关行,订舱代理 必填\n" +
            "name  名称 必填\n" +
            "profilePicture;//头像   放到司机专用的文件夹registerDriver\n" +
            "business_license  营业执照图片地址\n" +
            "roadTransportPermit 道路运输许可证(车队才有的)\n" +
            "agreement 合同(车队才有的)\n" +
            "agreementStart;//合同开始时间\n" +
            "agreementEnd;//合同结束时间\n" +
//            "salesman  业务员(我们组织的)\n" +
            "contacts  联系人\n" +
            "contactsPhone  联系人电话\n" +
            "address  地址\n" +
            "settle  结算周期(提醒用的)周结,月结 \n" +
            "offerLimitNum 客户下单数量限制\n" +
            "messageCode  验证码 \n" +
            "",httpMethod = "POST")
    @PostMapping("/register")
    public JsonResult register(CustomerCopy customer, User user) {
        try{
            customer.setState("");
            return customerService.ApiSaveWidthMessageCode(customer, new User(UserConstant.ADMIN_ID,UserConstant.ORGANIZATION_ID), user);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.error("注册失败: 用户名已被注册!");
        }
    }

    /**
     * 小程序注册用户
     */
    @ApiOperation(value = "小程序端司机注册",notes = "" +
            "username 帐号 必填\n" +
            "password 密码 必填\n" +
            "name 名字 必填\n" +
            "idCard 身份证 必填\n" +
            "carTeamId:车队id\n" +
            "carTeam:车队名称\n" +
            "carNo 车牌 必填\n" +
            "whiteCard:白卡号\n" +
            "operationLicense 车辆营运证图片\n" +
            "qualificationCertificate 司机从业资格证图片\n" +
            "",httpMethod = "POST")
    @PostMapping("/wechart/register")
    public JsonResult registerWechart(User user, Driver driver) {
//        try{
//            int userId = userService.apiSave(user);
//            return JsonResult.ok("注册成功!").put("userId",userId);
//        } catch (Exception e) {
//            return JsonResult.error("注册失败: 用户名已被注册!");
//        }
        try{
            return driverService.apiSave(driver, new User(UserConstant.ADMIN_ID,UserConstant.ORGANIZATION_ID), user);
        } catch (Exception e) {
            return JsonResult.error("注册失败: 用户名已被注册");
        }
    }

    /**
     * 微信公众平台token
     * 服务器地址(URL)  本地用        http://5rayz9.natappfree.cc/api/nt/login/gzh
     * 服务器地址(URL)  正式服务器用   http://gzh.sszgjzx.com
     */
    @ApiOperation(value = "微信公众平台token",notes = "" +
            "signature 公众号加密签名\n" +
            "timestamp 公众号时间戳\n" +
            "nonce 公众号随机数字\n" +
            "echostr 公众号随机字符串\n" +
            "",httpMethod = "GET")
    @GetMapping("/gzh")
    public String gzhValidate(String signature, String timestamp,
                                      String nonce, String echostr) throws AesException {

        if (WXPublicUtils.verifyUrl(signature, timestamp, nonce)) {
            System.out.println("公众号验证成功!");
            return echostr;
        }
        return null;
    }

    @PostMapping(value = "gzh")
    public void processMsg(HttpServletRequest request, HttpServletResponse response) throws IOException, DocumentException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        // 调用核心服务类接收处理请求
        Map<String, String> requestMap = wxservice.parseRequest(request.getInputStream());
        System.out.println(requestMap);
        //准备回复的数据包
        String resXml = wxservice.getRespose(requestMap);
//                "<xml>" +
//                "<ToUserName><![CDATA["+requestMap.get("FromUserName")+"]]></ToUserName>" +
//                "<FromUserName><![CDATA["+requestMap.get("ToUserName")+"]]></FromUserName>" +
//                "<CreateTime>"+ System.currentTimeMillis()/1000 +"</CreateTime>" +
//                "<MsgType><![CDATA[text]]></MsgType>" +
//                "<Content><![CDATA[why?]]></Content>" +
//                "</xml>";

        PrintWriter out = response.getWriter();
        System.out.println(resXml);
        out.print(resXml);
        out.flush();
        out.close();
//        ServletInputStream is = request.getInputStream();
//        byte[] b = new byte[1024];
//        int len;
//        StringBuilder sb = new StringBuilder();
//        while ((len=is.read(b))!=-1) {
//            sb.append(new String(b, 0, len));
//        }
    }


}
